package com.starblink.search.category.ui.list

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.starblink.android.basic.base.BaseViewModel
import com.starblink.android.basic.network.base.SkGqlClient
import com.starblink.rocketreserver.FetchSubForegroundCategoryQuery
import com.starblink.search.category.data.CategoryModel
import kotlinx.coroutines.launch

class ListVM : BaseViewModel() {

    var initCategoryId: String? = ""

    var initExpandModel: CategoryModel? = null

    var initExpandIndex: Int? = null

    val contentList = arrayListOf<CategoryModel>()

    val liveData = MutableLiveData<List<CategoryModel>>()

    fun loadInitData() {
        viewModelScope.launch {
            val oneCateList = SkGqlClient.skQuery(
                FetchSubForegroundCategoryQuery("0")
            )?.data?.fetchSubForegroundCategory?.map { CategoryModel(it.categoryF) }
            if (oneCateList?.isNotEmpty() == true) {
                contentList.addAll(oneCateList)
            }
            if (initCategoryId?.isNotEmpty() == true) {
                val children = SkGqlClient.skQuery(
                    FetchSubForegroundCategoryQuery(initCategoryId!!)
                )?.data?.fetchSubForegroundCategory?.map { CategoryModel(it.categoryF) }

                if (children?.isNotEmpty() == true) {
                    contentList.indexOfFirst { categoryModel -> categoryModel.source.id?.toString() == initCategoryId }
                        .takeIf { it > -1 }?.let {
                            val model = contentList[it]
                            model.expand = true
                            model.children = children
                            contentList.addAll(it + 1, children)
                            initExpandModel = model
                            initExpandIndex = it
                        }
                }
            }
            liveData.postValue(contentList)
            loadSuccess()
        }

    }

    fun queryChildren(id: String, result: ((children: List<CategoryModel>?) -> Unit)? = null) {
        viewModelScope.launch {
            showLoadDialog()
            val list = SkGqlClient.skQuery(
                FetchSubForegroundCategoryQuery(id)
            )?.data?.fetchSubForegroundCategory?.map { CategoryModel(it.categoryF) }
            result?.invoke(list)
            hideLoadDialog()
        }
    }


}